/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.grapeshot.halfnes;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

/**
 *
 * @author SDION
 */
public class MultiplayerDialog extends javax.swing.JDialog {

    private GUIImpl gui;
    private boolean multiplayerRomChosen = false;
     /**
     * Creates new form MultiplayerDialog
     */
    public MultiplayerDialog(java.awt.Frame parent) {
        super(parent, true);
        gui = (GUIImpl) parent;
        initComponents();

        this.setResizable(false);
        try {
            setLabels();
        } catch (IOException ex) {
            Logger.getLogger(MultiplayerDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void setLabels() throws IOException {
        try {
            /**
             * URL whatismyip = new URL("http://checkip.amazonaws.com/");
             * BufferedReader in = new BufferedReader(new InputStreamReader(
             * whatismyip.openStream())); String hostIP = in.readLine();
             */
            InetAddress i = InetAddress.getLocalHost();
            lblHostIP.setText(i.getHostAddress());

            setROMName();

        } catch (UnknownHostException ex) {
            Logger.getLogger(MultiplayerDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void setROMName() {
        lblSelectedROMHost.setText(gui.nes.getCurrentRomName());
        lblSelectedROMClient.setText(gui.nes.getCurrentRomName());
        if(!gui.nes.runEmulation)
           multiplayerRomChosen= false;
        else
            multiplayerRomChosen = true;
    }

    private void setStatuses() {
        setHostStatus();
        setClientStatus();
    }

    private void setHostStatus() {
        if (!gui.isHostRunning) {
            lblHostStatus.setText("Not running");
        }

        if (gui.isHostRunning && !gui.isClientConnected) {
            lblHostStatus.setText("Waiting for client");
        }

        if (gui.isHostRunning && gui.isClientConnected) {
            lblHostStatus.setText("Ready");
        }
    }

    private void setClientStatus() {
        if (gui.isHostRunning) {
            lblClientStatus.setText("Host already running");
        } else if (!gui.isConnectedToHost) {
            lblClientStatus.setText("Not connected");
        } else {
            lblClientStatus.setText("Connected to host");
        }
    }

    private void startServer() {
        if(gui.nes.passiveConnection.isConnected)
            JOptionPane.showMessageDialog(this, "You are already connected." );
        else{
            try {
                //Process proc = Runtime.getRuntime().exec("java -jar HalfNES.jar");            
                gui.nes.passiveConnection.startServer();
                gui.nes.StartNewDialog();
                int i = 0;
                while (!gui.nes.passiveConnection.isConnected) {
                    i++;
            }
                    lblClientIP.setText(gui.nes.passiveConnection.getIp());
            } catch (Exception ex) {
                    Logger.getLogger(MultiplayerDialog.class.getName()).log(Level.SEVERE, null, ex);
                }

                gui.isHostRunning = gui.nes.passiveConnection.isConnected;
                startHandshake();
            }

    }
    
    public void  startHandshake() {
        if(!multiplayerRomChosen){
            JOptionPane.showMessageDialog(this, "You have to choose a rom to load.");
        }  else   {
            
                //setROMName();
                if(!gui.nes.thing.runEmulation)
                    gui.nes.thing.loadROM(gui.ROMFilePath);

                gui.nes.passiveConnection.writeInt(9999);
                int i = 0;
                while(gui.nes.passiveConnection.readLine()!="ready")
                    i++;
                this.dispose();
                }
    }

    private void connectToHost() {
       if(gui.nes.passiveConnection.isConnected)
            JOptionPane.showMessageDialog(this, "You are already connected." );
        else{
            try {
            //Process proc = Runtime.getRuntime().exec("java -jar HalfNES.jar");
            gui.nes.passiveConnection.connectClient(txtHostIP.getText());
            gui.nes.StartNewDialog();
            } catch (Exception ex) {
                Logger.getLogger(MultiplayerDialog.class.getName()).log(Level.SEVERE, null, ex);
            }

            gui.isConnectedToHost = gui.nes.passiveConnection.isConnected;
            startHandshake();
       }

        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jDialog1 = new javax.swing.JDialog();
        jDialog2 = new javax.swing.JDialog();
        ClientTabbedPane = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lblHostIP = new javax.swing.JLabel();
        lblHostStatus = new javax.swing.JLabel();
        lblSelectedROMHost = new javax.swing.JLabel();
        btnStartServer = new javax.swing.JButton();
        btnSelectROMHost = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        btnKick = new javax.swing.JButton();
        lblClientIP = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        chkHostReady = new javax.swing.JCheckBox();
        jPanel2 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        txtHostIP = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        chkClientReady = new javax.swing.JCheckBox();
        btnConnect = new javax.swing.JButton();
        btnSelectROMClient = new javax.swing.JButton();
        lblClientStatus = new javax.swing.JLabel();
        lblSelectedROMClient = new javax.swing.JLabel();

        javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
        jDialog1.getContentPane().setLayout(jDialog1Layout);
        jDialog1Layout.setHorizontalGroup(
            jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jDialog1Layout.setVerticalGroup(
            jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jDialog2Layout = new javax.swing.GroupLayout(jDialog2.getContentPane());
        jDialog2.getContentPane().setLayout(jDialog2Layout);
        jDialog2Layout.setHorizontalGroup(
            jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jDialog2Layout.setVerticalGroup(
            jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        setTitle("Multiplayer");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        ClientTabbedPane.setMaximumSize(new java.awt.Dimension(81, 67));
        ClientTabbedPane.setSize(new java.awt.Dimension(81, 67));

        jLabel1.setText("ROM Selected : ");

        jLabel2.setText("My IP : ");

        jLabel3.setText("State : ");

        lblHostIP.setText("--");

        lblHostStatus.setText("--");

        lblSelectedROMHost.setText("--");

        btnStartServer.setText("Start Server");
        btnStartServer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStartServerActionPerformed(evt);
            }
        });

        btnSelectROMHost.setText("Select ROM");
        btnSelectROMHost.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelectROMHostActionPerformed(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Connected Player"));

        btnKick.setText("Kick");
        btnKick.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnKickActionPerformed(evt);
            }
        });

        lblClientIP.setText("--");

        jLabel4.setText("Client IP :");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblClientIP, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnKick)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(10, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(lblClientIP)
                    .addComponent(btnKick))
                .addGap(61, 61, 61))
        );

        chkHostReady.setText("Ready");
        chkHostReady.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkHostReadyActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(btnSelectROMHost)
                                .addGap(85, 85, 85)
                                .addComponent(jLabel1))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblHostIP, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnStartServer)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel3))
                            .addComponent(chkHostReady))
                        .addGap(0, 137, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap(363, Short.MAX_VALUE)
                        .addComponent(lblHostStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(lblSelectedROMHost, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(lblHostIP)
                    .addComponent(lblHostStatus)
                    .addComponent(btnStartServer))
                .addGap(4, 4, 4)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSelectROMHost)
                    .addComponent(jLabel1)
                    .addComponent(lblSelectedROMHost))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(chkHostReady)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        ClientTabbedPane.addTab("Host", jPanel1);

        jLabel5.setText("Host IP :");

        jLabel6.setText("State : ");

        jLabel7.setText("ROM Selected : ");

        chkClientReady.setText("Ready");
        chkClientReady.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkClientReadyActionPerformed(evt);
            }
        });

        btnConnect.setText("Connect");
        btnConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConnectActionPerformed(evt);
            }
        });

        btnSelectROMClient.setText("Select ROM");
        btnSelectROMClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelectROMClientActionPerformed(evt);
            }
        });

        lblClientStatus.setText("--");

        lblSelectedROMClient.setText("--");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(jPanel2Layout.createSequentialGroup()
                                        .addGap(0, 0, Short.MAX_VALUE)
                                        .addComponent(jLabel7)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(lblSelectedROMClient, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanel2Layout.createSequentialGroup()
                                        .addComponent(txtHostIP, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(btnConnect)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel6)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(lblClientStatus, javax.swing.GroupLayout.DEFAULT_SIZE, 139, Short.MAX_VALUE))))
                            .addComponent(chkClientReady)))
                    .addComponent(btnSelectROMClient))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtHostIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(btnConnect)
                    .addComponent(lblClientStatus))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSelectROMClient)
                    .addComponent(jLabel7)
                    .addComponent(lblSelectedROMClient))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(chkClientReady)
                .addContainerGap(139, Short.MAX_VALUE))
        );

        ClientTabbedPane.addTab("Client", jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(ClientTabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 521, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(ClientTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSelectROMHostActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectROMHostActionPerformed
        gui.loadROM();
        setROMName();
        if(gui.nes.passiveConnection.isConnected)
            startHandshake();
        
    }//GEN-LAST:event_btnSelectROMHostActionPerformed

    private void btnSelectROMClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectROMClientActionPerformed
        gui.loadROM();
        setROMName();
        if(gui.nes.passiveConnection.isConnected)
            startHandshake();
    }//GEN-LAST:event_btnSelectROMClientActionPerformed

    private void btnStartServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartServerActionPerformed
        startServer();
    }//GEN-LAST:event_btnStartServerActionPerformed

    private void chkHostReadyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkHostReadyActionPerformed
        this.dispose();
    }//GEN-LAST:event_chkHostReadyActionPerformed

    private void btnKickActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnKickActionPerformed
        gui.nes.passiveConnection.kickUser();
    }//GEN-LAST:event_btnKickActionPerformed

    private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed
        connectToHost();
    }//GEN-LAST:event_btnConnectActionPerformed

    private void chkClientReadyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkClientReadyActionPerformed
            this.dispose();
    }//GEN-LAST:event_chkClientReadyActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        setStatuses();
    }//GEN-LAST:event_formWindowOpened


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTabbedPane ClientTabbedPane;
    private javax.swing.JButton btnConnect;
    private javax.swing.JButton btnKick;
    private javax.swing.JButton btnSelectROMClient;
    private javax.swing.JButton btnSelectROMHost;
    private javax.swing.JButton btnStartServer;
    private javax.swing.JCheckBox chkClientReady;
    private javax.swing.JCheckBox chkHostReady;
    private javax.swing.JDialog jDialog1;
    private javax.swing.JDialog jDialog2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JLabel lblClientIP;
    private javax.swing.JLabel lblClientStatus;
    private javax.swing.JLabel lblHostIP;
    private javax.swing.JLabel lblHostStatus;
    private javax.swing.JLabel lblSelectedROMClient;
    private javax.swing.JLabel lblSelectedROMHost;
    private javax.swing.JTextField txtHostIP;
    // End of variables declaration//GEN-END:variables
}
